//
//  SWSharePresenter.swift
//  uicomponetTest3
//
//  Created by linhan on 16/3/14.
//  Copyright © 2016年 linhan. All rights reserved.
//

import Foundation
import UIKit



enum SWShareAction:Int
{
    case Cancel
    case QQ
    case WeixinSession
    case WeixinSpace
    case Weibo
    
    var icon:UIImage? {
            switch self {
            case .Cancel: return nil
            case .WeixinSession: return UIImage(named:"global_sharepresenter_wechat")
            case .WeixinSpace: return UIImage(named:"global_sharepresenter_moment")
            case .Weibo: return UIImage(named:"global_sharepresenter_weibo")
            case .QQ: return UIImage(named:"global_sharepresenter_qq")
            }
    }
    
    var title:String {
            switch self{
            case .Cancel: return "取消"
            case .WeixinSession: return "微信好友"
            case .WeixinSpace: return "微信朋友圈"
            case .Weibo: return "微博"
            case .QQ: return "QQ"
        }
    }
    
    var shareable:Bool
    {
        return self == .WeixinSession || self == .WeixinSpace || self == .Weibo || self == .QQ
    }
    
    static func getShareChannelFormAction(action:SWShareAction) -> SWShareChannel
    {
        if action == .WeixinSession
        {
            return .WechatSession
        }
        else if action == .WeixinSpace
        {
            return .WechatSpace
        }
        else if action == .QQ
        {
            return .QQ
        }
        return .Weibo
    }
}


private let _instance = SWSharePresenter()
class SWSharePresenter: NSObject,SWPopupContainerDelegate
{
    typealias ActionCallback = (SWShareAction) -> Void
    
    lazy private var _shareView:SWShareView = SWShareView()
    lazy private var _popupContainer:PopupContainer = PopupContainer()
    
    class var instance:SWSharePresenter {
        return _instance
    }
    
    override init()
    {
        super.init()
        setup()
    }
    
    func show(actions:[SWShareAction], callback:@escaping ActionCallback)
    {
        _shareView.clickCallback = {[weak self] action in
            self?.close(true)
            if action != .Cancel
            {
                callback(action)
            }
        }
        _shareView.show(actions:actions, containerWidth: UIScreen.main.bounds.width)
        _popupContainer.show(_shareView)
    }
    
    func show(callback:@escaping ActionCallback)
    {
        let actions:[SWShareAction] = [.WeixinSession, .WeixinSpace, .QQ, .Weibo]
        show(actions: actions, callback:callback)
    }
    
    func close(_ animated:Bool = true)
    {
        _popupContainer.close(animated)
    }
    
    func willPresentPopupContainer()
    {
        _shareView.y = UIScreen.main.bounds.height
        UIView.animate(withDuration: 0.2, animations: {
            self._shareView.alpha = 1
            self._shareView.y = UIScreen.main.bounds.height - self._shareView.height
        })
    }
    
    func willDismissPopupContainer()
    {
        UIView.animate(withDuration: 0.2, animations: {
            self._shareView.alpha = 0
            self._shareView.y = UIScreen.main.bounds.height
        })
    }
    
    private func setup()
    {
        _popupContainer.delegate = self
    }
}

private class SWShareView:UIView
{
    var clickCallback:((SWShareAction) -> Void)?
    
    private let ButtonContainerHeight:CGFloat = 40
    //左右边距
    private let ButtonContainerMargin:CGFloat = 12
    
    lazy private var _titleLabel:UILabel = UILabel()
    lazy private var _buttons:[SWShareAction:UIButton] = [:]
    lazy private var _buttonContainer:UIView = UIView()
    lazy private var _topLine:UIView = UIView()
    lazy private var _bottomLine:UIView = UIView()
    lazy private var _cancelBtn:UIButton = UIButton(type: .system)
    
    init() {
        super.init(frame: CGRectZero)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setup()
    {
        backgroundColor = UIColor.white
        
        _titleLabel.textColor = UIColor(hex: 0x313131)
        _titleLabel.font = UIFont.systemFont(ofSize:14)
        _titleLabel.textAlignment = .center
        _titleLabel.frame = CGRectMake(0, 9, 0, 18)
        _titleLabel.text = "分享到"
        addSubview(_titleLabel)
        
        _buttonContainer.frame = CGRectMake(ButtonContainerMargin, _titleLabel.bottom + 14, 0, ButtonContainerHeight)
        addSubview(_buttonContainer)
        
        _cancelBtn.titleLabel?.font = UIFont.systemFont(ofSize:14)
        _cancelBtn.setTitleColor(UIColor(hex:0x333232), for: .normal)
        _cancelBtn.setTitle(SWShareAction.Cancel.title, for: .normal)
        _cancelBtn.layer.cornerRadius = 10
        _cancelBtn.layer.masksToBounds = true
        _cancelBtn.backgroundColor = UIColor(hex: 0xf0f0f0)
        _cancelBtn.addTarget(self, action: #selector(cancelBtnTapped), for: .touchUpInside)
        _cancelBtn.frame = CGRectMake(ButtonContainerMargin, _buttonContainer.bottom + 30, 0, 56)
        addSubview(_cancelBtn)
        
        
        frame = CGRectMake(0, 0, 0, _cancelBtn.bottom + 12)
    }
    
    func show(actions:[SWShareAction], containerWidth:CGFloat)
    {
        var buttons:[UIButton] = []
        _buttonContainer.removeAllSubview()
        
        for action in actions
        {
            if action != .Cancel
            {
                var button:UIButton? = _buttons[action]
                if button == nil
                {
                    button = UIButton(type: .custom)
                    button?.setImage(action.icon, for: UIControlState.normal)
                    button?.sizeToTouchEasy()
                    button?.height = ButtonContainerHeight
                    button?.tag = action.rawValue
                    button?.addTarget(self, action: #selector(actionBtnTapped(_:)), for: .touchUpInside)
                    _buttons[action] = button
                }
                if let button = button
                {
                    buttons.append(button)
                    _buttonContainer.addSubview(button)
                }
            }
        }
        _titleLabel.width = containerWidth
        _buttonContainer.frame = CGRectMake(ButtonContainerMargin, _buttonContainer.y, containerWidth - 2 * ButtonContainerMargin, _buttonContainer.height)
        LayoutUtil.distributeHAverageWelt(buttons, containerWidth: _buttonContainer.width)
        _cancelBtn.width = _buttonContainer.width
        width = containerWidth
    }
    
    @objc private func cancelBtnTapped()
    {
        clickCallback?(.Cancel)
    }
    
    @objc private func actionBtnTapped(_ button:UIButton)
    {
        if let action = SWShareAction(rawValue: button.tag)
        {
            clickCallback?(action)
        }
    }
}


